<?php
/**
 * 百大-澳雅姐供应商SDK
 * @author 陈韵
 */
namespace App\Service\VendorClient\Shopaoyajie;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;
use Hyperf\Utils\WaitGroup;

class ShopaoyajieApiClient
{
    private $account  = 'Shopaoyajie';
    protected $config;
    protected $RouteMap = [
        'queryGoodsList'        => '/Api/Stock/CnStock/Sku',
        'queryGoodsPrice'       => '/Api/Price/getChannelPrice',
        'createOrder'           => '/Api/Df/DfOrder/Create',
        'queryOrderExpress'     => '/Api/Df/DfOrder/Df',
        'getAccessToken'        => '/Api/Token/getToken',
    ];
    

    public function __construct($apiBody = []){
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return mixed
     */
/**
     * 创建订单
     */
    public function createOrder( $params = [] )
    {
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo1");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];
        $orderGood = current($params['orderGoods']);
        
        //数量
        $OrderQty  =  bcmul((int)$orderGood["quantity"],(int)$orderGood["spec_num"]);
        //供应商sku
        $Barcode   = $orderGood["supplier_skucode"];
        
        $data = [
            'ReciverAddr'           => $orderInfo["province"].$orderInfo["city"].$orderInfo["district"].$orderInfo["receive_address"],
            'WarehouseNo'           => $this->config["WarehouseNo"],
            'ReciverName'           => $orderInfo["receive_name"],
            'ReciverCountryCode'    => "100",
            'OrderQty'              => (int)$OrderQty,
            'Barcode'               => $Barcode,
            'ClientOrderNo'         => $orderInfo['supplier_dsn'],
            'Issubmit'              => 1,
            'ReciverPhone'          => $orderInfo["recveive_phone"],
            'TrafficType'           => (int)$this->config["TrafficType"],
        ];
        
        $token = $this->getToken();
        if($token["code"] != Normal::SUC ){
            return $token;
        }
        //创建订单数据
        $requestParam = [
            'method'    => 'createOrder',
            'token'     => $token["data"],
            'data'      => $data,
        ];
        $res  = $this->execute($requestParam);
        if( $res['code'] == Normal::SUC ) {
            $thirdpart_order_sn =  $res["data"]["result"]["Data"]["SerialNum"];
            return Normal::returnCode(Normal::SUC,"订单推送成功",[
                'thirdpart_order_sn' => $thirdpart_order_sn
            ]);
        }
        return $res;
    }
    
    /**
     * 查询物流单信息
     * @param array $param
     */
    public function queryOrderExpress( $param = [] )
    {
        $token = $this->getToken();
        if($token["code"] != Normal::SUC ){
            return $token;
        }
        $requestParam = [
            'method'    => 'queryOrderExpress',
            'token'     => $token["data"],
            'data'      => [
                'serialNum' =>  $param['thirdpart_order_sn'],
            ]
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 查询商品信息
     */
    public function queryGoodsList($param = [])
    {
        $token = $this->getToken();
        if($token["code"] != Normal::SUC ){
            return Normal::returnCode(Normal::FAIL,$token['msg'],[
                'has_next'  => true,
                'total'     => 0,
                'list'      => []
            ]);
        }
        $details=[];
        foreach ($param["skuNos"] as $sku){
            $requestParam = [
                'method'    => 'queryGoodsList',
                'token'     => $token["data"],
                'data'      => [
                    'barcode' => $sku
                ],
            ];
            $responseParam = $this->execute($requestParam);
            if ($responseParam['code']== Normal::SUC && isset($responseParam['data']['result']) && !empty($responseParam['data']['result'])){
                $result = $responseParam['data']['result'];
                //通过ProductCode得到商品的成本价
                $priceInfo = $this->queryGoodsPrice($result["ProductCode"]);
                if($priceInfo["code"] == Normal::SUC && !empty($priceInfo["data"])){
                    $result["price"] = $priceInfo["data"];
                }else{
                    $result["price"] = 0.00;
                }
                $details[] = $result;
            }
        }
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'has_next'  => true,
            'total'     => count($details),
            'list'      => $details
        ]);
    }
//     /**
//      * 查询商品信息
//      */
//     public function queryGoodsList($param = [])
//     {
//         $token = $this->getToken();
//         if($token["code"] != Normal::SUC ){
//             return $token;
//         }
//         $skuNos = $param["skuNos"];
//         $details=[];
//         $goodsList = [];
//         $count=count($skuNos);
//         $wg = new WaitGroup();
//         $wg->add($count);
//         foreach ($skuNos as $sku){
//             co(function () use ($wg,$sku,& $details,$token) {
//                 $data =[
//                     'barcode' => $sku
//                 ];
//                 $requestParam = [
//                     'method'    => 'queryGoodsList',
//                     'token'     => $token["data"],
//                     'data'      => $data,
//                 ];
//                 $responseParam = $this->execute($requestParam);
//                 if ($responseParam['code']==Normal::SUC && isset($responseParam['data']['result']) && !empty($responseParam['data']['result'])){
//                     $result = $responseParam['data']['result'];
//                     //通过ProductCode得到商品的成本价
//                     $price = $this->queryGoodsPrice($result["ProductCode"]);
//                     $result["price"] = $price;
//                     $details[] = $result;
//                 }
//                 $wg->done();
//             });
//         }
//         $wg->wait();
//         return Normal::returnCode(Normal::SUC,"获取成功",$details);
//     }

    /**
     * 查询商品详情
     */
    public function queryGoodsPrice($ProductNo)
    {
        $price = 0.00;
        $data = [
            'WarehouseCode'         => $this->config["WarehouseNo"],
            'ProductNos'            => [(string)$ProductNo],
            'PageSize'              => 1,
            'CurrentPageIndex'      => 1
        ];
        $token = $this->getToken();
        if($token["code"] != Normal::SUC ){
            return $token;
        }
        $details = [];
        //查询商品价格
        $requestParam = [
            'method'    => 'queryGoodsPrice',
            'token'     => $token["data"],
            'data'      => $data,
        ];
        $responseParam  = $this->execute($requestParam);
        if($responseParam["code"] == Normal::SUC && isset($responseParam["data"]["result"]["Data"]["Data"]) && !empty($responseParam["data"]["result"]["Data"]["Data"])){
               
            $productInfo = current($responseParam["data"]["result"]["Data"]["Data"]);
            //成本=(realPrice*4/1.1)  ”()”内的结果保留2位小数，一直四舍五入到1.13】
            
            $realPrice = bcmul($productInfo["RealPrice"],4,3);
            $realPrice = bcdiv($realPrice,1.1,2);
            $price     = round($realPrice);
        }

        return Normal::returnCode(Normal::SUC,"请求成功",$price);
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    private function getToken( $param = [])
    {
        $redis = redis();
        $cache_key = $this->account."_AccessToken";
        $token = $redis->get($cache_key);
        $time = time();
        //判断token是否存在
        if(empty($token)) {
            $parameter = [
                'method'    => 'getAccessToken',
                'data'      => [
                    'user'      => $this->config["user"],
                    'password'  => $this->config["password"],
                ],
            ];
            $res =$this->execute($parameter);
            if( $res['code'] != Normal::SUC ) {
                return $res;
            }
            $token  = $res["data"]["result"]["token"];
            $redis->set($cache_key,$token,60*5);
        }
        return Normal::returnCode(Normal::SUC,"获取成功",$token);
    }
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] ){

        if(empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        $method         = $param['method'];
        $url            = $this->config['baseurl'].$this->RouteMap[$method];
        if( in_array($method,['queryOrderExpress','queryGoodsList']) ) {
            $Method = "GET";
            $url = $url."?token=".$param["token"]."&".http_build_query($param["data"]);
        }else if($method == 'getAccessToken'){
            $Method = "GET";
            $url = $url."?".http_build_query($param["data"]);
        }else{
            $Method = "POST";
            $url = $url."?token=".$param["token"];
        }
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $param["data"],
                'method'    => $Method,
                'format'    => 'json',
                'header'    => [
                    "content-type: application/json"
                ],
            ],
        ];

        if( in_array($method,['queryGoodsList','queryGoodsPrice','getAccessToken']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = @json_decode($res,true);
        if(isset($resHttp['code']) && $resHttp['code'] == 200 ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp);
        }
        $message = isset($resHttp['message']) ? $resHttp['message'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }
    
}